package com.back_end.Reflection;

import com.TestDemo.TestBean;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PerformanceTest {


    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IllegalAccessException, InstantiationException {

            long l = 1000*1000*1000L;


            test(l);
            test1(l);
            test2(l);

    }


    public static void test(long l){
        // 普通方式调用
        TestBean testBean = new TestBean();
        long startTime = System.currentTimeMillis();

        for (long i = 0; i <l; i++) {
            testBean.getName();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("普通方式，时间为："+(endTime-startTime));


    }

    public static void test1(long l) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        // 反射方式调用
        Class testBeanClass = Class.forName("com.TestDemo.TestBean");

        Constructor testBeanConstructor = testBeanClass.getConstructor(String.class, int.class); // 有参构造器
        Constructor constructor = testBeanClass.getConstructor(null); // 无参构造器

        TestBean zjz = (TestBean)testBeanConstructor.newInstance("zjz", 18);  // 获取有参对象
        TestBean testBean = (TestBean)constructor.newInstance(null);  // 获取无参对象

        Method getName = testBeanClass.getMethod("getName", null); // 获取getName无参方法

        long startTime = System.currentTimeMillis();

        for (long i = 0; i <l; i++) {
            getName.invoke(testBean,null);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("反射方式，时间为："+(endTime-startTime));

        // 反射方式调用，关闭检测
    }



    public static void test2(long l) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        // 反射方式调用
        Class testBeanClass = Class.forName("com.TestDemo.TestBean");

        Constructor testBeanConstructor = testBeanClass.getConstructor(null); // 获取无参构造器
        TestBean testBean = (TestBean)testBeanConstructor.newInstance(null);  // 获取无参对象
        Method getName = testBeanClass.getMethod("getName", null); // 获取getName无参方法

        getName.setAccessible(true);
        long startTime = System.currentTimeMillis();

        for (long i = 0; i <l; i++) {
            getName.invoke(testBean,null);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("反射关闭检测，时间为："+(endTime-startTime));

        // 反射方式调用，关闭检测
    }

}
